<template>
  <div class="menu">
    <span @click="showMenu">点击</span>
    <span>粘贴的内容:{{ printFont }}</span>
  </div>
</template>
<script setup>
const { ref } = require("vue");
const { Menu, MenuItem, getCurrentWindow, clipboard } =
  require("electron").remote;
var menu = new Menu();
// 定义粘贴版内容变量
const printFont = ref();
// 监听鼠标右键
window.addEventListener("contextmenu", (e) => {
  e.preventDefault();
  clickMouseRight();
});
const clickMouseRight = () => {
  if (!window.getSelection().isCollapsed) {
    menu.append(
      new MenuItem({
        label: "复制",
        accelerator: "CommandOrControl+C",
        click: copyString,
      })
    );
    menu.append(
      new MenuItem({
        label: "粘贴",
        accelerator: "CommandOrControl+V",
        click: printString,
      })
    );
    menu.popup(getCurrentWindow());
  }
};
// 复制操作
const copyString = () => {
  console.log("copy");
  //getSelection(); // 获取选中内容
  clipboard.writeText(getSelection());
};
// 粘贴操作
const printString = () => {
  console.log("printString");
  if (document.activeElement) {
    // clipboard.readText() // 获取剪贴板内容
    printFont.value = clipboard.readText(); // 写入焦点元素
    clipboard.clear(); // 清空剪贴板
  }
};
// 获取选中内容
const getSelection = () => {
  var text = "";
  if (window.getSelection) {
    // 除IE9以下 之外的浏览器
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type !== "Control") {
    //IE9以下，可不考虑
    text = document.selection.createRange().text;
  }
  if (text) {
    return text;
  }
};
</script>
<style scoped>
@import url("../layout/public/common.css");
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #108ba1;
  padding: 10px 20px;
  font-size: 22px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #0adfff;
  line-height: 40px;
  cursor: pointer;
}
</style>
